package com.example.coursemanagement.service.impl;

import com.example.coursemanagement.MyUtils.CommonResult;
import com.example.coursemanagement.MyUtils.PathUtils;
import com.example.coursemanagement.mapper.UserMessgaeImgMapper;
import com.example.coursemanagement.pojo.UserMessageImg;
import com.example.coursemanagement.service.UploadService;
import com.example.coursemanagement.service.UserMessageImgService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;

import javax.annotation.Resource;
import java.io.InputStream;

@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {

    @Resource
    private UserMessageImgService userMessageImgService;

    @Resource
    private UserMessgaeImgMapper userMessgaeImgMapper;

    @Override
    @Transactional
    public CommonResult uploadImg(Integer userId, Integer messageId, MultipartFile img) {
        //判断文件类型或者文件大小
        String originalFilename = img.getOriginalFilename();
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")) {
            return CommonResult.failed("文件类型错误");
        }
        //文件上传到七牛云并返回外链
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img, filePath);
        UserMessageImg userMessageImg = new UserMessageImg();
        userMessageImg.setUserId(userId);
        userMessageImg.setMessageId(messageId);
        userMessageImg.setImgPath(url);
        userMessgaeImgMapper.insert(userMessageImg);
        return CommonResult.success(url);
    }

    private String accessKey;
    private String secretKey;
    private String bucket;

    //文件上传的方法
    private String uploadOss(MultipartFile headImg, String filePath) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
            InputStream inputStream = headImg.getInputStream();//获取文件的流
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return "http://s4qhbfqc6.hb-bkt.clouddn.com/"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "头像上传出现异常";

    }
}
